package api

import (
	"net/http"
	"reflect"

	"github.com/gin-gonic/gin"
)

type ResponseJson struct {
	Status int    `json:"-"`
	Code   int    `json:"code,omitempty" name:"code"`
	Data   any    `json:"data,omitempty" name:"data"`
	Msg    string `json:"message,omitempty" name:"message"`
	Total  int64  `json:"total,omitempty" name:"message"`
}

// 处理返回,当用户不输入任务值时也有返回
func trimResponse(ctx *gin.Context, status int, resData ResponseJson) {
	if reflect.DeepEqual(resData, ResponseJson{}) {
		ctx.AbortWithStatus(status)
		return
	}
	ctx.AbortWithStatusJSON(status, resData)
}

// status : 可以用户自定义传,也有默认值
func checkStatusCode(preset int, resData ResponseJson) int {
	if resData.Status == 0 {
		return preset
	}
	return resData.Status
}

func Okay(ctx *gin.Context, resData ResponseJson) {
	code := checkStatusCode(http.StatusOK, resData)
	if resData.Code == 0 {
		resData.Code = 200
	}
	trimResponse(ctx, code, resData)
}
func Fail(ctx *gin.Context, resData ResponseJson) {
	trimResponse(ctx, checkStatusCode(http.StatusBadRequest, resData), resData)
}

// 服务器错误
func ServerFail(ctx *gin.Context, resData ResponseJson) {
	trimResponse(ctx, checkStatusCode(http.StatusBadGateway, resData), resData)
}
